package com.mofang.ticketing.common.excel.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.mofang.ticketing.common.core.exception.BizException;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel 工具类
 */
public class ExcelUtils {

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param clazz     Excel clazz 头
     * @param data      数据列表哦
     * @param <T>       泛型，保证 clazz 和 data 类型的一致性
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> clazz, List<T> data) {

        try {
            // 输出 Excel
            EasyExcel.write(response.getOutputStream(), clazz)
                    .excelType(ExcelTypeEnum.XLSX)
//                    .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
//                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 最大 255 宽度
                    .sheet(sheetName).doWrite(data);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        } catch (IOException e) {
            response.reset();
            throw new BizException("导出EXCEL异常");
        }

    }

    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)  // 不要自动关闭，交给 Servlet 自己处理
                .doReadAllSync();
    }

}
